/*
 * Created on 20/04/2008
 *
 */

package com.apbetioli.mapr.project.webservice;

import com.apbetioli.mapr.project.control.ProjectsControl;
import com.apbetioli.mapr.project.schema.ProjectsManager;
import com.apbetioli.mapr.util.properties.PropertiesLoaderImpl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author Alexandre Parra Betioli
 */
@WebService()
public class WSProjects {

    private JAXBContext jc;
    private final String SCHEMA_PACKAGE = PropertiesLoaderImpl.getValue("config.properties", "project.schema");

    /**
     * Operação de serviço web
     */
    @WebMethod(operationName = "process")
    public String process(@WebParam(name = "xml") final String xml) {

        try {
            jc = JAXBContext.newInstance( SCHEMA_PACKAGE );
            
            ProjectsManager pm = unmarshall(xml);
            ProjectsControl pc = new ProjectsControl();
            ProjectsManager response = pc.process(pm);
            return marshall(response);

        } catch (Exception ex) {
            Logger.getLogger(WSProjects.class.getName()).log(Level.SEVERE, null, ex);

            return "<? xml version=\"1.0\"?>                          \n" + 
                   "<ProjectsManager>                                 \n" + 
                   "    <Error>                                       \n" + 
                   "       <Message>Exception</Message>               \n" +
                   "       <Details>" + ex.getMessage() + "</Details> \n" +
                   "    </Error>                                      \n" + 
                   "</ProjectsManager>                                \n";
        }
        
    }

    private ProjectsManager unmarshall(String xml) throws JAXBException {

        Unmarshaller    um = jc.createUnmarshaller();

        StringReader    sr = new StringReader(xml);
        BufferedReader  br = new BufferedReader(sr);
        ProjectsManager pm = (ProjectsManager) um.unmarshal(br);

        return pm;
    }

    private String marshall(ProjectsManager pm) throws JAXBException {

        StringWriter   sw = new StringWriter();
        BufferedWriter bw = new BufferedWriter(sw);

        Marshaller marsh = jc.createMarshaller();
        marsh.marshal(pm, bw);

        return sw.toString();
    }
    
}
